//
//  SetVC.swift
//  whale
//
//  Created by topnet on 2022/7/26.
//

import UIKit
import RxSwift

final class SetVC: ICBaseVC {

    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
    
    override func _initUI() {
        super._initUI()
        navBar.titleV.text = "设置"
        if WitWork.share.user != nil {
            listV.tableFooterView = logOutBtn
        }
        view.addSubview(listV)
    }
    
    override func _initData() {
        let cacheSize = getCacheFileSize()
        let dataSource = [
            MeModel(footerHeight: 10.adapter,
                    rows: [
                HeadTailModel(title: "清除缓存", content: cacheSize, hasArrow: false),
                HeadTailModel(title: "关于我们", vcType: AboutVC.self),
            ]),
        ]
        listV.configData(data: dataSource, cellType: HeadTailCell.self) { [weak self] path, md, cell in
            
        } itemSelected: { [weak self] path, md in
            LogUtil.log(path)
            if let mod = md as? HeadTailModel {
                if let vcType = mod.vcType {
                    self?.push(type: vcType)
                }else if path.section == 0 &&  path.row == 0 {
                    mod.content = self?.clearCache()
                    self?.listV.reloadRows(at: [path], with: .fade)
                }
            }
        }
    }
    
    private func actionLogOut() {
        AlertUtil.alert(title: "是否退出登录", isAutoDissMiss: true, rightHandler:  { [weak self] in
            WitWork.share.logout()
            self?.backUtil()
        })
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        listV.left_right(view).top(UIScreen.navH).bottom(view.bounds.height-view.safeAreaInsets.bottom)
    }
    
    private lazy var disposeBag = DisposeBag()
    
    lazy var listV: GroupedListView = {
        let v = GroupedListView(frame: .zero, style: .grouped)
        v.cellType = MeCell.self
        v.separatorColor = .separator
        v.separatorInset = UIEdgeInsets(x: 12.adapter)
        return v
    }()

    
    private lazy var logOutBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.backgroundColor = .white
        btn.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: 50.adapter)
        btn.setTitle("退出", for: .normal)
        btn.setTitleColor(.title, for: .normal)
        btn.rx.tap.throttle(.milliseconds(800), scheduler: MainScheduler.instance).subscribe(onNext: { [weak self] in
            self?.actionLogOut()
        }).disposed(by: disposeBag)
        return btn
    }()
}


extension SetVC {
    private func getCacheFileSize()-> String {
        var foldSize: UInt64 = 0
        guard let filePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
            return ""
        }
        if let files = FileManager.default.subpaths(atPath: filePath) {
            for path in files {
                let temPath = filePath + "/" + path
                let folder = try? FileManager.default.attributesOfItem(atPath: temPath)
                if let s = folder?[.size] as? UInt64 {
                    foldSize += s
                }
            }
        }
        
        if foldSize > 1024*1024 {
            return String(format: "%.2f", Double(foldSize)/1024/1024) + "MB"
        }
        if foldSize > 1024 {
            return String(format: "%.2f", Double(foldSize)/1024) + "KB"
        }
        
        return String(foldSize) + "B"
    }
    
    private func clearCache()-> String {
        guard let filePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
            return ""
        }
        if let files = FileManager.default.subpaths(atPath: filePath) {
            for path in files {
                let temPath = filePath + "/" + path
                if FileManager.default.fileExists(atPath: temPath) {
                    try? FileManager.default.removeItem(atPath: temPath)
                }
            }
        }
        return getCacheFileSize()
    }
}
